<?php

class sfCheckboxWithallWidget extends sfWidgetFormChoice
{
  
  public function __construct($options = array(), $attributes = array())
  {
   $options['multiple'] = true;
   $options['expanded'] = true;           
   parent::__construct($options, $attributes);
  }  

  /**
   * Renders the widget.
   *
   * @param  string $name        The element name
   * @param  string $value       The value selected in this widget
   * @param  array  $attributes  An array of HTML attributes to be merged with the default HTML attributes
   * @param  array  $errors      An array of errors for the field
   *
   * @return string An HTML tag string
   *
   * @see sfWidgetForm
   */
  public function render($name, $value = null, $attributes = array(), $errors = array())
  {
    if ($this->getOption('multiple'))
    {
      $attributes['multiple'] = 'multiple';

      if ('[]' != substr($name, -2))
      {
        $name .= '[]';
      }
    }

    if (!$this->getOption('renderer') && !$this->getOption('renderer_class') && $this->getOption('expanded'))
    {
      unset($attributes['multiple']);
    }

    $select_all_check = new sfWidgetFormInputCheckbox();
    $select_all_id = $this->generateId('all_'.$name);
    
    $js = <<<OEF
   <script type="text/javascript">
       $(document).ready(function(){
            $('#{$select_all_id}').click(function(){                
                checked_val = $(this).attr('checked');
                $(this).parents('.content:first').find('.checkbox_list input').each(function(){
                    $(this).attr('checked', checked_val);
                });
            });
            
            $('#{$select_all_id}').parents('.content:first').find('.checkbox_list input').click(function(){
                if($(this).attr('checked') == false && $('#{$select_all_id}').attr('checked')==true){
                    $('#{$select_all_id}').attr('checked', false);
                }
            });
       });
   </script>    
OEF
;
    
    return 
        '<div class="select_all_cont">'.$select_all_check->render('all_'.$name).'<label>'.__('Select all').'</label></div>'.
        '<div class="clear"></div>'.
        $this->getRenderer()->render($name, $value, $attributes, $errors).$js;
  }
}
